package com.blrs.service.collaborative.impl;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.annotation.Resource;

import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.exception.ServiceException;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.uuid.UUID;
import com.blrs.domain.*;
import com.blrs.mapper.*;
import com.blrs.service.collaborative.ICollaborationApprovalService;

import com.blrs.system.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 协作审批服务实现类
 *
 * @author ruoyi
 * @date 2024-04-15
 */
@Service
public class CollaborationApprovalServiceImpl implements ICollaborationApprovalService {

    private static final Logger log = LoggerFactory.getLogger(CollaborationApprovalServiceImpl.class);

    // 常量定义
    private static final String CLASSIFICATION_ID = "650c44e1-b575-4b62-9d54-1ba9d1e8abb7";
    private static final String ENTERPRISE_SOURCE = "15";
    private static final String ACTIVE_STATUS = "1";
    private static final String DEL_FLAG_NORMAL = "0";
    private static final String APPROVAL_PASS = "0";
    private static final String STATE_APPROVED = "2";
    private static final String STATE_REJECTED = "3";
    private static final String COMPANY_TYPE_ENTERPRISE = "0";
    private static final String NOT_PROXY = "未代理";

    @Resource
    private CollaborationApprovalMapper collaborationApprovalMapper;
    @Resource
    private CollaborativeManagementMapper collaborativeManagementMapper;
    @Resource
    private SupplierInfoMapper supplierInfoMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private EnterpriseInfoMapper enterpriseInfoMapper;
    @Resource
    private ProductListMapper productListMapper;
    @Resource
    private QualificationInfoMapper qualificationInfoMapper;

    @Override
    public CollaborationApproval selectCollaborationApprovalByReviewId(String reviewId) {
        return collaborationApprovalMapper.selectCollaborationApprovalByReviewId(reviewId);
    }

    @Override
    public List<CollaborationApproval> selectCollaborationApprovalList(CollaborationApproval collaborationApproval) {
        return collaborationApprovalMapper.selectCollaborationApprovalList(collaborationApproval);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCollaborationApproval(CollaborationApproval collaborationApproval) {
        try {
            validateApproval(collaborationApproval);

            if (APPROVAL_PASS.equals(collaborationApproval.getReviewResult())) {
                handleApprovalPass(collaborationApproval);
            } else {
                handleApprovalReject(collaborationApproval);
            }

            setApprovalInfo(collaborationApproval);
            return collaborationApprovalMapper.insertCollaborationApproval(collaborationApproval);
        } catch (Exception e) {
            log.error("处理协作审批失败", e);
            throw new ServiceException("处理协作审批失败: " + e.getMessage());
        }
    }

    private void validateApproval(CollaborationApproval collaborationApproval) {
        if (collaborationApproval == null || StringUtils.isEmpty(collaborationApproval.getCollaborativeId())) {
            throw new ServiceException("无效的审批信息");
        }
    }

    private void handleApprovalPass(CollaborationApproval collaborationApproval) {
        CollaborativeManagement collaborativeManagement = updateCollaborativeStatus(
                collaborationApproval.getCollaborativeId(),
                STATE_APPROVED
        );

        handleSupplierInfo(collaborativeManagement);
        handleEnterpriseInfo(collaborativeManagement);
    }

    private void handleApprovalReject(CollaborationApproval collaborationApproval) {
        updateCollaborativeStatus(collaborationApproval.getCollaborativeId(), STATE_REJECTED);
    }

    private CollaborativeManagement updateCollaborativeStatus(String collaborativeId, String status) {
        CollaborativeManagement collaborativeManagement = collaborativeManagementMapper
                .selectCollaborativeManagementByCollaborativeId(collaborativeId);
        if (collaborativeManagement == null) {
            throw new ServiceException("未找到对应的协作管理记录");
        }

        collaborativeManagement.setState(status);
        collaborativeManagementMapper.updateCollaborativeManagement(collaborativeManagement);
        return collaborativeManagement;
    }

    private void setApprovalInfo(CollaborationApproval collaborationApproval) {
        collaborationApproval.setReviewerId(SecurityUtils.getUserId().toString());
        collaborationApproval.setReviewer(SecurityUtils.getUsername());
        collaborationApproval.setReviewTime(new Timestamp(System.currentTimeMillis()));
    }

    private void handleSupplierInfo(CollaborativeManagement collaborativeManagement) {
        handleRecipientSupplierInfo(collaborativeManagement);
        handleInitiatorSupplierInfo(collaborativeManagement);
    }

    private void handleRecipientSupplierInfo(CollaborativeManagement collaborativeManagement) {
        SysDept sysDept = sysDeptMapper.selectDeptById(Long.parseLong(collaborativeManagement.getInitiatorId()));
        if (COMPANY_TYPE_ENTERPRISE.equals(sysDept.getCompanyType())) {
            return;
        }

        SupplierInfo existingSupplier = supplierInfoMapper.selectEnterpriseNameByName(
                collaborativeManagement.getInitiatorName(),
                collaborativeManagement.getRecipientId()
        );

        if (existingSupplier == null) {
            createNewSupplierInfo(collaborativeManagement, sysDept, true);
        } else {
            updateExistingSupplierInfo(existingSupplier, collaborativeManagement, true);
        }

        // 处理产品清单
        handleProductList(collaborativeManagement, true);
    }

    private void handleInitiatorSupplierInfo(CollaborativeManagement collaborativeManagement) {
        SysDept deptInfo = sysDeptMapper.selectDeptById(Long.parseLong(collaborativeManagement.getRecipientId()));
        if (COMPANY_TYPE_ENTERPRISE.equals(deptInfo.getCompanyType())) {
            return;
        }

        SupplierInfo existingSupplier = supplierInfoMapper.selectEnterpriseNameByName(
                collaborativeManagement.getRecipientName(),
                collaborativeManagement.getInitiatorId()
        );

        if (existingSupplier == null) {
            createNewSupplierInfo(collaborativeManagement, deptInfo, false);
        } else {
            updateExistingSupplierInfo(existingSupplier, collaborativeManagement, false);
        }

        // 处理产品清单
        handleProductList(collaborativeManagement, false);
    }

    private void createNewSupplierInfo(CollaborativeManagement collaborativeManagement,
                                       SysDept sysDept,
                                       boolean isRecipient) {
        SupplierInfo supplierInfo = new SupplierInfo();
        supplierInfo.setEnterpriseId(UUID.randomUUID().toString());
        supplierInfo.setEnterpriseName(isRecipient ?
                collaborativeManagement.getInitiatorName() :
                collaborativeManagement.getRecipientName());
        supplierInfo.setEnterpriseOrgId(Long.parseLong(isRecipient ?
                collaborativeManagement.getInitiatorId() :
                collaborativeManagement.getRecipientId()));
        supplierInfo.setBelongTo(isRecipient ?
                collaborativeManagement.getRecipientId() :
                collaborativeManagement.getInitiatorId());

        setSupplierBaseInfo(supplierInfo, sysDept, collaborativeManagement, isRecipient);
        supplierInfoMapper.insertSupplierInfo(supplierInfo);
    }

    private void setSupplierBaseInfo(SupplierInfo supplierInfo,
                                     SysDept sysDept,
                                     CollaborativeManagement collaborativeManagement,
                                     boolean isRecipient) {
        supplierInfo.setIndustryType(sysDept.getCompanyType());
        supplierInfo.setClassificationId(CLASSIFICATION_ID);
        supplierInfo.setEnterpriseNature(sysDept.getNature());
        supplierInfo.setEnterpriseNo(generateEnterpriseNo(sysDept.getCompanyType(),
                supplierInfo.getBelongTo()));
        supplierInfo.setRegisteredCapital(sysDept.getRegisteredFund());
        supplierInfo.setEnterpriseSource(ENTERPRISE_SOURCE);
        supplierInfo.setEnterpriseAddress(sysDept.getAddress());
        supplierInfo.setIndustry(sysDept.getIndustry());
        supplierInfo.setLegalRepresentative(sysDept.getLegalPerson());

        try {
            if (StringUtils.isNotEmpty(sysDept.getFoundTime())) {
                supplierInfo.setEstablishmentDate(
                        new SimpleDateFormat("yyyy-MM-dd").parse(sysDept.getFoundTime())
                );
            }
        } catch (ParseException e) {
            log.error("日期解析失败", e);
        }

        setSupplierContactInfo(supplierInfo, sysDept);
        setSupplierManagementInfo(supplierInfo, collaborativeManagement, isRecipient);
        setSupplierAuditInfo(supplierInfo, collaborativeManagement, isRecipient);
    }

    private void setSupplierContactInfo(SupplierInfo supplierInfo, SysDept sysDept) {
        supplierInfo.setAdministrativeArea(sysDept.getArea());
        supplierInfo.setContacts(sysDept.getContacts());
        supplierInfo.setTelephone(sysDept.getPhone());
        supplierInfo.setBusinessScope(sysDept.getBusinessScope());
    }

    private void setSupplierManagementInfo(SupplierInfo supplierInfo,
                                           CollaborativeManagement collaborativeManagement,
                                           boolean isRecipient) {
        if (isRecipient) {
            supplierInfo.setDevelopmentId(SecurityUtils.getUserId());
            supplierInfo.setDevelopmentManager(SecurityUtils.getUsername());
            supplierInfo.setTransactionId(SecurityUtils.getUserId());
            supplierInfo.setBusinessManager(SecurityUtils.getUsername());
        } else {
            supplierInfo.setDevelopmentId(Long.parseLong(collaborativeManagement.getCreateId()));
            supplierInfo.setDevelopmentManager(collaborativeManagement.getCreateName());
            supplierInfo.setTransactionId(Long.parseLong(collaborativeManagement.getCreateId()));
            supplierInfo.setBusinessManager(collaborativeManagement.getCreateName());
        }
        supplierInfo.setStatus(ACTIVE_STATUS);
    }

    private void setSupplierAuditInfo(SupplierInfo supplierInfo,
                                      CollaborativeManagement collaborativeManagement,
                                      boolean isRecipient) {
        if (isRecipient) {
            supplierInfo.setCreationId(SecurityUtils.getUserId().toString());
            supplierInfo.setCreationName(SecurityUtils.getUsername());
            supplierInfo.setOperateId(SecurityUtils.getUserId());
            supplierInfo.setDepartmentId(SecurityUtils.getDeptId());
            supplierInfo.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
            supplierInfo.setOrganizationId(SecurityUtils.getOrgId());
            supplierInfo.setOrganizationName(SecurityUtils.getOrgName());
        } else {
            supplierInfo.setCreationId(collaborativeManagement.getCreateId());
            supplierInfo.setCreationName(collaborativeManagement.getCreateName());
            supplierInfo.setOperateId(Long.parseLong(collaborativeManagement.getCreateId()));
            supplierInfo.setDepartmentId(collaborativeManagement.getDepartmentId());
            supplierInfo.setDepartmentName(collaborativeManagement.getDepartmentName());
            supplierInfo.setOrganizationId(collaborativeManagement.getOrganizationId());
            supplierInfo.setOrganizationName(collaborativeManagement.getOrganizationName());
        }
        supplierInfo.setCreationTime(new Timestamp(System.currentTimeMillis()));
        supplierInfo.setOperateTime(new Timestamp(System.currentTimeMillis()));
        supplierInfo.setDelFlag(DEL_FLAG_NORMAL);
    }

    private void handleProductList(CollaborativeManagement collaborativeManagement, boolean isRecipient) {
        QualificationInfo qualificationInfo = new QualificationInfo();
        qualificationInfo.setOrganizationId(Long.valueOf(isRecipient ?
                collaborativeManagement.getInitiatorId() :
                collaborativeManagement.getRecipientId()));
        qualificationInfo.setProductStatus("已上架");

        List<QualificationInfo> qualificationInfos = qualificationInfoMapper
                .selectQualificationInfoList(qualificationInfo);

        for (QualificationInfo qualification : qualificationInfos) {
            createProductList(qualification, collaborativeManagement, isRecipient);
        }
    }

    private void createProductList(QualificationInfo qualification,
                                   CollaborativeManagement collaborativeManagement,
                                   boolean isRecipient) {
        // 先获取供应商信息
        SupplierInfo supplierInfo = supplierInfoMapper.selectEnterpriseNameByName(
            isRecipient ? collaborativeManagement.getInitiatorName() : collaborativeManagement.getRecipientName(),
            isRecipient ? collaborativeManagement.getRecipientId() : collaborativeManagement.getInitiatorId()
        );
        
        if (supplierInfo == null) {
            log.error("未找到对应的供应商信息");
            return;
        }

        ProductList productList = new ProductList();
        productList.setId(UUID.randomUUID().toString());
        // 使用供应商的enterpriseId
        productList.setEnterpriseId(supplierInfo.getEnterpriseId());
        productList.setProductName(qualification.getProductName());
        productList.setProductType(qualification.getProductType());
        productList.setProductSpecs(qualification.getProductSpecs());
        productList.setProductRemark(qualification.getProductRemark());
        productList.setReleaseTime(qualification.getReleaseTime());
        productList.setIsProxy(NOT_PROXY);
        productList.setOrganizationId(Long.parseLong(isRecipient ? 
            collaborativeManagement.getRecipientId() : 
            collaborativeManagement.getInitiatorId()));
        productList.setOrganizationName(isRecipient ? 
            collaborativeManagement.getRecipientName() : 
            collaborativeManagement.getInitiatorName());
        productList.setCreationTime(new Timestamp(System.currentTimeMillis()));
        productList.setCreateId(SecurityUtils.getUserId());
        productList.setCreateName(SecurityUtils.getUsername());
        
        productListMapper.insertProductList(productList);
    }

    private void handleEnterpriseInfo(CollaborativeManagement collaborativeManagement) {
        handleEnterpriseInfoForParty(collaborativeManagement, true);  // 处理发起方
        handleEnterpriseInfoForParty(collaborativeManagement, false); // 处理接收方
    }

    private void handleEnterpriseInfoForParty(CollaborativeManagement collaborativeManagement,
                                              boolean isInitiator) {
        SysDept dept = sysDeptMapper.selectDeptById(Long.parseLong(isInitiator ?
                collaborativeManagement.getInitiatorId() :
                collaborativeManagement.getRecipientId()));

        if (!COMPANY_TYPE_ENTERPRISE.equals(dept.getCompanyType())) {
            return;
        }

        String enterpriseName = isInitiator ?
                collaborativeManagement.getInitiatorName() :
                collaborativeManagement.getRecipientName();
        String belongTo = isInitiator ?
                collaborativeManagement.getRecipientId() :
                collaborativeManagement.getInitiatorId();

        Long existingCount = enterpriseInfoMapper.number(enterpriseName, belongTo);
        if (existingCount == 0) {
            createNewEnterpriseInfo(collaborativeManagement, dept, isInitiator);
        }
    }

    private void createNewEnterpriseInfo(CollaborativeManagement collaborativeManagement,
                                         SysDept dept,
                                         boolean isInitiator) {
        EnterpriseInfo enterpriseInfo = new EnterpriseInfo();
        enterpriseInfo.setMarkAs("1");
        enterpriseInfo.setEnterpriseOrgId(isInitiator ?
                collaborativeManagement.getInitiatorId() :
                collaborativeManagement.getRecipientId());
        enterpriseInfo.setEnterpriseName(isInitiator ?
                collaborativeManagement.getInitiatorName() :
                collaborativeManagement.getRecipientName());
        enterpriseInfo.setBelongTo(isInitiator ?
                collaborativeManagement.getRecipientId() :
                collaborativeManagement.getInitiatorId());

        setEnterpriseBaseInfo(enterpriseInfo, dept);
        setEnterpriseManagementInfo(enterpriseInfo, collaborativeManagement, isInitiator);

        enterpriseInfoMapper.insertEnterpriseInfo(enterpriseInfo);
    }

    private void setEnterpriseBaseInfo(EnterpriseInfo enterpriseInfo, SysDept dept) {
        enterpriseInfo.setEnterpriseId(UUID.randomUUID().toString());
        enterpriseInfo.setIndustryType(dept.getCompanyType());
        enterpriseInfo.setClassificationId(CLASSIFICATION_ID);
        enterpriseInfo.setEnterpriseNature(dept.getNature());

        String maxNo = enterpriseInfoMapper.getMaxEnterpriseNo(enterpriseInfo.getBelongTo());
        enterpriseInfo.setEnterpriseNo(StringUtils.isEmpty(maxNo) ? 1 : Integer.parseInt(maxNo) + 1);

        enterpriseInfo.setRegisteredCapital(dept.getRegisteredFund());
        enterpriseInfo.setEnterpriseSource(ENTERPRISE_SOURCE);
        enterpriseInfo.setEnterpriseAddress(dept.getAddress());
        enterpriseInfo.setIndustry(dept.getIndustry());
        enterpriseInfo.setLegalRepresentative(dept.getLegalPerson());
        enterpriseInfo.setStatus(ACTIVE_STATUS);
        enterpriseInfo.setDelFlag(DEL_FLAG_NORMAL);

        try {
            if (StringUtils.isNotEmpty(dept.getFoundTime())) {
                enterpriseInfo.setEstablishmentDate(
                        new SimpleDateFormat("yyyy-MM-dd").parse(dept.getFoundTime())
                );
            }
        } catch (ParseException e) {
            log.error("日期解析失败", e);
        }

        enterpriseInfo.setAdministrativeArea(dept.getArea());
        enterpriseInfo.setContacts(dept.getContacts());
        enterpriseInfo.setTelephone(dept.getPhone());
        enterpriseInfo.setBusinessScope(dept.getBusinessScope());
    }

    private void setEnterpriseManagementInfo(EnterpriseInfo enterpriseInfo,
                                             CollaborativeManagement collaborativeManagement,
                                             boolean isInitiator) {
        if (isInitiator) {
            enterpriseInfo.setDevelopmentId(SecurityUtils.getUserId());
            enterpriseInfo.setDevelopmentManager(SecurityUtils.getUsername());
            enterpriseInfo.setTransactionId(SecurityUtils.getUserId());
            enterpriseInfo.setBusinessManager(SecurityUtils.getUsername());
            enterpriseInfo.setCreationId(SecurityUtils.getUserId().toString());
            enterpriseInfo.setCreationName(SecurityUtils.getUsername());
            enterpriseInfo.setOperateId(SecurityUtils.getUserId());
            enterpriseInfo.setDepartmentId(SecurityUtils.getDeptId());
            enterpriseInfo.setDepartmentName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
            enterpriseInfo.setOrganizationId(SecurityUtils.getOrgId());
            enterpriseInfo.setOrganizationName(SecurityUtils.getOrgName());
        } else {
            enterpriseInfo.setDevelopmentId(Long.parseLong(collaborativeManagement.getCreateId()));
            enterpriseInfo.setDevelopmentManager(collaborativeManagement.getCreateName());
            enterpriseInfo.setTransactionId(Long.parseLong(collaborativeManagement.getCreateId()));
            enterpriseInfo.setBusinessManager(collaborativeManagement.getCreateName());
            enterpriseInfo.setCreationId(collaborativeManagement.getCreateId());
            enterpriseInfo.setCreationName(collaborativeManagement.getCreateName());
            enterpriseInfo.setOperateId(Long.parseLong(collaborativeManagement.getCreateId()));
            enterpriseInfo.setDepartmentId(collaborativeManagement.getDepartmentId());
            enterpriseInfo.setDepartmentName(collaborativeManagement.getDepartmentName());
            enterpriseInfo.setOrganizationId(collaborativeManagement.getOrganizationId());
            enterpriseInfo.setOrganizationName(collaborativeManagement.getOrganizationName());
        }

        enterpriseInfo.setCreationTime(new Timestamp(System.currentTimeMillis()));
        enterpriseInfo.setOperateTime(new Timestamp(System.currentTimeMillis()));
    }

    private String generateEnterpriseNo(String companyType, String belongTo) {
        String prefix = "1".equals(companyType) ? "GYS" : "PT";
        SupplierInfo query = new SupplierInfo();
        query.setBelongTo(belongTo);

        List<SupplierInfo> existingSuppliers = "1".equals(companyType) ?
                supplierInfoMapper.selectSupplierInfoList(query) :
                supplierInfoMapper.selectCooperativeRelationshipList(query);

        int sequence = existingSuppliers.size() + 1;

        if (sequence < 10) {
            return prefix + "000" + sequence;
        } else if (sequence < 100) {
            return prefix + "00" + sequence;
        } else if (sequence < 1000) {
            return prefix + "0" + sequence;
        }
        return prefix + sequence;
    }

    @Override
    public int updateCollaborationApproval(CollaborationApproval collaborationApproval) {
        return collaborationApprovalMapper.updateCollaborationApproval(collaborationApproval);
    }

    @Override
    public int deleteCollaborationApprovalByReviewIds(String[] reviewIds) {
        return collaborationApprovalMapper.deleteCollaborationApprovalByReviewIds(reviewIds);
    }

    @Override
    public int deleteCollaborationApprovalByReviewId(String reviewId) {
        return collaborationApprovalMapper.deleteCollaborationApprovalByReviewId(reviewId);
    }


    private void updateExistingSupplierInfo(SupplierInfo existingSupplier,
                                            CollaborativeManagement collaborativeManagement,
                                            boolean isRecipient) {
        // 保留原有ID
        String enterpriseId = existingSupplier.getEnterpriseId();

        // 更新基础信息
        SysDept sysDept = sysDeptMapper.selectDeptById(Long.parseLong(isRecipient ?
                collaborativeManagement.getInitiatorId() :
                collaborativeManagement.getRecipientId()));

        // 设置更新信息
        existingSupplier.setEnterpriseId(enterpriseId);  // 保持原有ID
        existingSupplier.setEnterpriseName(isRecipient ?
                collaborativeManagement.getInitiatorName() :
                collaborativeManagement.getRecipientName());
        existingSupplier.setEnterpriseOrgId(Long.parseLong(isRecipient ?
                collaborativeManagement.getInitiatorId() :
                collaborativeManagement.getRecipientId()));
        existingSupplier.setBelongTo(isRecipient ?
                collaborativeManagement.getRecipientId() :
                collaborativeManagement.getInitiatorId());

        // 更新其他信息
        setSupplierBaseInfo(existingSupplier, sysDept, collaborativeManagement, isRecipient);

        // 更新数据库记录
        supplierInfoMapper.updateSupplierInfo(existingSupplier);

        log.info("更新供应商信息成功, enterpriseId: {}", enterpriseId);
    }
}